﻿namespace EyeOpen.UI.Silverlight
{
    using System;
    using System.Windows.Input;

    public class RelayCommand : ICommand
    {
        private readonly Action executeMethod;
        private readonly Func<bool> canExecuteMethod;

        public RelayCommand()
        {
        }

        public RelayCommand(Action executeMethod)
            : this(executeMethod, null)
        {
            this.executeMethod = executeMethod;
        }

        public RelayCommand(Action executeMethod, Func<bool> canExecuteMethod)
        {
            this.executeMethod = executeMethod;
            this.canExecuteMethod = canExecuteMethod;
        }

        public event EventHandler CanExecuteChanged;

        public void Execute(object parameter)
        {
            if (executeMethod != null)
            {
                executeMethod();
            }

            UpdateCanExecuteState();
        }

        public void UpdateCanExecuteState()
        {
            if (CanExecuteChanged != null)
            {
                CanExecuteChanged(this, new EventArgs());
            }
        }

        public virtual bool CanExecute(object parameter)
        {
            if (canExecuteMethod != null)
            {
                return canExecuteMethod();
            }

            return true;
        }
    }
}